package com.example.administrator.myapplication.media;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;


/**
 * Created by Administrator on 2016/3/23 0023.
 */
public class Music {

    private static AudioManager mAudioManager;
    private static MediaPlayer mMediaPlayer;

    //是否打开音效
    public static boolean isMusicOn = true;
    //最大音量
    public static int MAX_VOLUME = 0;
    //当前音量
    public static int Curr_VOLUME = 0;
    //初始化
    public static void init(Context context){
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        MAX_VOLUME = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        Curr_VOLUME = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        mMediaPlayer=null;
    }
    //设置音量
    public static void setVolume(int volume){
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,volume,0);
        Curr_VOLUME = volume;
    }

    //播放音乐
    public  static void startMusic(Context context,boolean isLoop,int resId){
        if(!isMusicOn){
            return;
        }
        if(mMediaPlayer!=null){
            return;
        }
        mMediaPlayer = MediaPlayer.create(context, resId);
        mMediaPlayer.setLooping(isLoop);
        mMediaPlayer.start();


    }
    //停止音乐
    public static void stopMusic(){
        if(mMediaPlayer==null){
            return;
        }
        if(mMediaPlayer.isPlaying()){
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer=null;
        }

    }
    //保存用户偏好设置
    public static void save(Context context){
        SharedPreferences sharedPref = context.getSharedPreferences("music",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean("isMusicOn",isMusicOn);
        editor.putInt("curr_volume",Curr_VOLUME);
        editor.commit();
    }

    public static void load(Context context){
        SharedPreferences sharedPref = context.getSharedPreferences("music",Context.MODE_PRIVATE);
        sharedPref.getBoolean("isMusicOn",true);
        sharedPref.getInt("curr_volume",3);

    }


}
